package com.example.contentcenter.service.content;

import com.example.contentcenter.dao.content.ShareMapper;
import com.example.contentcenter.domain.dto.content.ShareAuditDTO;
import com.example.contentcenter.domain.dto.content.ShareDTO;
import com.example.contentcenter.domain.dto.user.UserDTO;
import com.example.contentcenter.domain.entity.content.Share;
import com.example.contentcenter.domain.messaging.UserAddBonusMsgDTO;
import com.example.contentcenter.feignclient.UserCenterFeignClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

/**
 * @ClassName: ShareService
 * @Author: lerry_li
 * @CreateDate: 2021/05/30
 * @Description
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
public class ShareService {
    private final ShareMapper shareMapper;
    private final UserCenterFeignClient userCenterFeignClient;
    private final RocketMQTemplate rocketMQTemplate;

    public ShareDTO finById(Integer id) {
        //获取分享详情
        Share share = this.shareMapper.selectByPrimaryKey(id);
        //获取发布人id
        Integer userId = share.getUserId();
        //服务发现
        //用HTTP GET方法,Feign
        UserDTO userDTO = userCenterFeignClient.findById(id);
        //消息装配
        ShareDTO shareDTO = new ShareDTO();
        BeanUtils.copyProperties(share, shareDTO);
        shareDTO.setWxNickname(userDTO.getWxNickname());
        return shareDTO;
    }

    public Share auditById(Integer id, ShareAuditDTO shareAuditDTO) {
        //1.查询share是否存在，不存在或者当前的audit_status!=NOT_YET,则抛异常
        Share share = this.shareMapper.selectByPrimaryKey(id);
        if (share == null) throw new IllegalArgumentException("参数非法！该分享不存在！");
        if (!Objects.equals("NOT_YET", share.getAuditStatus()))
            throw new IllegalArgumentException("参数非法！该分享已审核通过/不通过！");
        //2.审核资源，将状态设为PASS/REJECT
        share.setAuditStatus(shareAuditDTO.getAuditStatusEnum().toString());
        this.shareMapper.updateByPrimaryKey(share);
        //3.若为PASS，为发布人增加积分
        //异步执行
        //发送消息给mq，让用户中心去消费，并为发布人添加积分
        // destination:表示topic  playload:表示？
        this.rocketMQTemplate.convertAndSend("add-bonus",
                UserAddBonusMsgDTO.builder()
                        .userId(share.getUserId())
                        .bonus(50)
                        .build());
        return share;
    }
}
